package com.uchedao.seller.util;

import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.uchedao.seller.config.GlobalInfo;
import com.upyun.block.api.listener.CompleteListener;
import com.upyun.block.api.listener.ProgressListener;
import com.upyun.block.api.main.UploaderManager;
import com.upyun.block.api.utils.UpYunUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 * 图片异步上传
 * Created by hang on 2015/9/22.
 */
public class UploadPicUtil {

    private String API_SECRET = "a3q6z6hheUR96OH7B08eDjtawwA=";
    // 空间名
    String bucket = "uchedao";

    private Context mContext;

    public UploadPicUtil(Context context) {
        this.mContext = context;
    }



    public void upSinglePic(String moduleName, String filePath, UpSinglePicCallback callback) {
        new UpSingleTask(moduleName, filePath, callback).execute();
    }

    public class UpSingleTask extends AsyncTask<Void, Void, String> {
        private String moduleName;
        private String filePath;
        private String fileUrl;
        private UpSinglePicCallback callback;

        public UpSingleTask(String moduleName, String filePath, UpSinglePicCallback callback) {
            this.moduleName = moduleName;
            this.filePath = filePath;
            this.callback = callback;
            fileUrl = "/"
                    + new SimpleDateFormat("yyyyMM").format(new Date())
                    + "/"
                    + System.currentTimeMillis()
                    + new Random().nextInt(9)
                    + Util.getFileName(filePath);
        }

        @Override
        protected String doInBackground(Void... params) {
            if(TextUtils.isEmpty(filePath))
                return "";

                String picUrl = GlobalInfo.dbHelper.getPhotoFileId(filePath);
                if(picUrl == null) {
                    File localFile = new File(filePath);
                    if(!localFile.exists()) {
                        if(callback != null)
                            callback.uploadCallback(false, localFile.getName()+" not found", moduleName);
                        return "";
                    }

                    // 本地未保存图片网络路径
                    try {
                        ProgressListener progressListener = new ProgressListener() {
                            @Override
                            public void transferred(long transferedBytes, long totalBytes) {
                            }
                        };

                        CompleteListener completeListener = new CompleteListener() {
                            @Override
                            public void result(boolean isComplete, String result, String error) {
//                                System.out.println("isComplete:" + isComplete + ";result:" + result + ";error:" + error);
                                if(callback != null)
                                    callback.uploadCallback(isComplete, fileUrl, moduleName);
                                if(isComplete)
                                    GlobalInfo.dbHelper.insertPhoto(filePath, fileUrl);
                            }
                        };

                        UploaderManager uploaderManager = UploaderManager.getInstance(bucket);
                        uploaderManager.setConnectTimeout(60);
                        uploaderManager.setResponseTimeout(60);
                        Map<String, Object> paramsMap = uploaderManager.fetchFileInfoDictionaryWith(localFile, fileUrl);
                        paramsMap.put("x-gmkerl-quality", 70);
                        String policyForInitial = UpYunUtils.getPolicy(paramsMap);
                        String signatureForInitial = UpYunUtils.getSignature(paramsMap, API_SECRET);
                        uploaderManager.upload(policyForInitial, signatureForInitial, localFile, progressListener, completeListener);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    if(callback != null)
                        callback.uploadCallback(true, picUrl, moduleName);
                }
            return "ok";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }

    public interface UpSinglePicCallback {
        public void uploadCallback(boolean isSucceed, String result, String moduleName);
    }
}
